package com.sali;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: zhang hang
 * @date: 2022/7/19 12:14.
 * @version: 1.0
 */
public class FunnelProblem {

    private static Map<String, Funnel> funnelMap = new HashMap<>();

    static class Funnel {
        private BigDecimal waterRate;
        private Integer capacity;
        private Integer leftCapacity;
        private Long leakTimes;

        public Funnel(BigDecimal waterRate, Integer capacity) {
            this.waterRate = waterRate;
            this.capacity = capacity;
            this.leftCapacity = capacity;
            this.leakTimes = System.currentTimeMillis();
        }

        // 水流出，空间增加
        public void runningWater() {
            long nowTime = System.currentTimeMillis();
            long deltaTime = nowTime - leakTimes;
            int deltaCapacity = waterRate.multiply(new BigDecimal(deltaTime)).intValue();
            // deltaCapacity用于统计出水量
            if (deltaCapacity < 0) {
                this.leftCapacity = capacity;
                this.leakTimes = nowTime;
                return;
            }
            if (deltaCapacity < 1) {
                return;
            }
            this.leftCapacity += deltaCapacity;
            this.leakTimes = nowTime;
            if (this.leftCapacity < this.capacity) {
                this.leftCapacity = this.capacity;
            }
        }

        // 水流入，空间减少
        public boolean watering(Integer waterCapacity) {
            runningWater();
            if (leftCapacity > waterCapacity) {
                this.leftCapacity -= waterCapacity;
                return true;
            }
            return false;
        }
    }

    public boolean allow(String key, Integer initCapacity, BigDecimal leakRate) {
        Funnel funnel = funnelMap.get(key);
        if (funnel == null) {
            funnel = new Funnel(leakRate, initCapacity);
            funnelMap.put(key, funnel);
        }
        return funnel.watering(1);
    }


    public static void main(String[] args) {
        FunnelProblem funnelProblem = new FunnelProblem();

        for (int i = 0; i < 20; i++) {
            Boolean allow = funnelProblem.allow("browser", 10, BigDecimal.valueOf(0.1));
            if (allow) {
                System.out.println("you can broser");
            } else {
                System.out.println("pls wait");
            }
        }
    }

}
